package classtest;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

public class LinkedHashMapDemo {
    public static void main1(String[] args) {
        Map<Integer, String> map1 = new HashMap<>();//Map底层是 Hash表 + 单链表
        map1.put(1, "张三");
        map1.put(3, "张三");
        map1.put(2, "张三");
        System.out.println("map1 = " + map1);//map1 = {1=张三, 2=张三, 3=张三}
        // HashMap的put方法，添加元素时，会无序，因为在添加的时候，会进行哈希计算，将元素添加到对应的位置，Integer的hash值就是其本身
        // LinkedHashMap的put方法，添加元素时，会按照添加的顺序进行排序 , 因为LinkedHashMap底层是 双链表 + Hash表 + 单链表
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        map.put(1, "张三");
        map.put(6, "张三");
        map.put(2, "张三");
        map.put(3, "张三");
        System.out.println("map = " + map);//map = {1=张三, 6=张三, 2=张三, 3=张三}

        System.out.println("-----------------");

    }
    public static void main(String[] args) {
        LinkedHashMap<Student, String> map = new LinkedHashMap<>();
        map.put(new Student("张三", 18), "张三");
        map.put(new Student("张三", 18), "张三");//这是new出来的两个对象，地址值不一样，所以没有被覆盖
        System.out.println("map = " + map);//发现有两个元素，重复没有被覆盖，因为没有重写equals和hashCode方法
        LinkedHashMap<String, String> map1 = new LinkedHashMap<String, String>();
        map1.put("张三", "张三");
        map1.put("张三", "张三02");
        System.out.println("map1 = " + map1);
    }
}
class Student{
    private String name;
    private int age;
    public Student() {
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}